package com.easyadmin.pro.modules.sys.controller;

import com.easyadmin.pro.common.constants.HttpConstants;
import com.easyadmin.pro.common.constants.SystemConstants;
import com.easyadmin.pro.common.controller.BaseController;
import com.easyadmin.pro.common.page.Pageable;
import com.easyadmin.pro.common.vo.RestResult;
import com.easyadmin.pro.modules.sys.entity.RouterEntity;
import com.easyadmin.pro.modules.sys.entity.UserPermissionsEntity;
import com.easyadmin.pro.modules.sys.entity.UserRoleEntity;
import com.easyadmin.pro.modules.sys.query.RouterQueryVo;
import com.easyadmin.pro.modules.sys.service.IRouterService;
import com.easyadmin.pro.modules.sys.service.IUserPermissionsService;
import com.easyadmin.pro.modules.sys.vo.RouterInfoVo;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;

/**
 *  控制层。
 *
 * @author xulin
 * @since 2024-04-02
 */
@RestController
@RequestMapping(HttpConstants.SYS_MODULE_PATH + "/router/")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RouterController extends BaseController {

    private final IRouterService iRouterService;

    private final IUserPermissionsService userPermissionsService;

    /**
     * 添加。
     *
     * @param routerInfoVo
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("save")
    public RestResult save(@RequestBody RouterInfoVo routerInfoVo) {
        RouterEntity routerEntity = new RouterEntity();
        BeanUtils.copyProperties(routerInfoVo, routerEntity);
        if (Objects.isNull(routerEntity.getParentId())) {
            routerEntity.setParentId(0L);
        }
        return success(iRouterService.saveOrUpdate(routerEntity));
    }

    /**
     * 批量保存
     * @param routerInfos
     * @return
     */
    @PostMapping("batch")
    public RestResult batch(@RequestBody List<RouterInfoVo> routerInfos) {
        List<RouterEntity> saveInfos = com.easyadmin.pro.tool
                .BeanUtils.conventBeans(routerInfos, RouterEntity.class);
        return success(iRouterService.saveBatch(saveInfos));
    }

    /**
     * 获取路由信息
     * @param userId
     * @return
     */
    @GetMapping("info/{userId}")
    public RestResult info(@PathVariable String userId) {
        List<Long> routerIds = userPermissionsService.listAs(new QueryWrapper()
                .select(UserPermissionsEntity::getRouterId)
                .from(UserPermissionsEntity.class)
                .leftJoin(UserRoleEntity.class).on(UserPermissionsEntity::getRoleId, UserRoleEntity::getRoleId)
                .eq(UserRoleEntity::getUserId, userId), Long.class);
        List<RouterEntity> routerInfos = iRouterService.list(new QueryWrapper().in(RouterEntity::getId, routerIds));
        return success(com.easyadmin.pro.tool.BeanUtils.conventBeans(routerInfos, RouterInfoVo.class));
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("remove/{id}")
    public RestResult remove(@PathVariable Serializable id) {
        return success(iRouterService.removeById(id));
    }

    /**
     * 更新路由状态。
     *
     * @param routerInfo
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("disabledRouter")
    public RestResult disabledRouter(@RequestBody RouterInfoVo routerInfo) {
        return success(iRouterService.disabledRouter(routerInfo));
    }

    /**
     * 查询所有。
     *
     * @return 所有数据
     */
    @GetMapping("list")
    public RestResult list() {
        return success(iRouterService.list());
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("getInfo/{id}")
    public RestResult getInfo(@PathVariable Serializable id) {
        return success(iRouterService.getById(id));
    }

    /**
     * 分页查询。
     *
     * @param routerQuery 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public RestResult page(RouterQueryVo routerQuery) {
        return success(Pageable.of(routerQuery, (() -> iRouterService.queryRouterPage(routerQuery))));
    }


    /**
     * 刷新缓存
     * @return
     */
    @PostMapping("refresh")
    public RestResult refresh() {
        iRouterService.refresh(SystemConstants.ROUTER_KEY);
        return success();
    }

    /**
     * 获取缓存路由
     * @return
     */
    @GetMapping("cacheRouter")
    public RestResult cacheRouter() {
        return success(iRouterService.cacheRouter());
    }

    /**
     * 获取路由信息
     * @param routerId
     * @return
     */
    @GetMapping("getRouterInfo/{routerId}")
    public RestResult getRouterInfo(@PathVariable Long routerId) {
        RouterEntity routerInfo = iRouterService.getById(routerId);
        RouterInfoVo routerInfoVo = new RouterInfoVo();
        BeanUtils.copyProperties(routerInfo, routerInfoVo);
        Long parentId = routerInfo.getParentId();
        if (Objects.nonNull(parentId) && !Objects.equals(0L, parentId)) {
            RouterEntity parentRouterInfo = iRouterService.getById(parentId);
            RouterInfoVo parentRouterInfoVo = new RouterInfoVo();
            BeanUtils.copyProperties(parentRouterInfo, parentRouterInfoVo);
            parentRouterInfoVo.setValue(parentRouterInfoVo.getTitle());
            routerInfoVo.setParentInfo(parentRouterInfoVo);
        }
        return success(routerInfoVo);
    }

}
